package org.parademo.service;

import org.parademo.dao.ProposalStatusDao;
import org.parademo.model.ProposalStatusEntity;
import org.parademo.service.model.ProposalStatusCode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProposalStatusServiceImpl implements ProposalStatusService {
    private final ProposalStatusDao proposalStatusDao;

    private Map<String, ProposalStatusEntity> statuses;

    public ProposalStatusServiceImpl(ProposalStatusDao proposalStatusDao) {
        this.proposalStatusDao = proposalStatusDao;
    }

    private void loadStatusesIfNeeded() {
        if (statuses != null) {
            return;
        }

        this.statuses = new HashMap<String, ProposalStatusEntity>();

        List<ProposalStatusEntity> loadedStatuses = proposalStatusDao.getStatuses();

        for (ProposalStatusEntity loadedStatus : loadedStatuses) {
            ProposalStatusEntity status = new ProposalStatusEntity(loadedStatus);

            statuses.put(
                    status.getCode(),
                    status
            );
        }
    }

    @Override
    public ProposalStatusEntity getByCode(ProposalStatusCode code) {
        loadStatusesIfNeeded();

        return statuses.get(code.name());
    }

    @Override
    public void submitProposal(Long proposalId) {
        proposalStatusDao.submitProposal(proposalId);
    }
}
